import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button, Steps, Icon, Menu, Dropdown, Progress, Tooltip } from 'antd';
import styles from '../Users.css';
import Factory from '../../factory';
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import dataImportCreate from '../../addons/DataImport'
import * as common from '../../../utils/common';
import xlsxTmp from '../../../assets/申请公司新客户.xlsx'
import * as datetime from '../../../utils/datetime'
const daoName = "COMP_DFGZFlow";
const ButtonGroup = Button.Group; 
const renderStep = (data) => {
    const { progress, status } = data
    const percent = Math.round(progress)
    return <Progress percent={percent} size="small" status={status === "" ? "normal" : status} />
};
let columns = [
    { title: "当前进度", key: "StepName", render: data => renderStep(data), width: 170, dispaly: true },
    { title: '申请人', dataIndex: 'SQR', key: 'SQR', width: 120, sorter: true, dispaly: true, filter: true, export: true },
    { title: '申请时间', key: 'CREATETIME', render: data => datetime.format(data.CREATETIME, "yyyy-MM-dd"), width: 140, sorter: true, dispaly: true, filter: true, export: false },
    { title: '完结时间', dataIndex: 'UPDATETIME', key: 'UPDATETIME', width: 180, sorter: true, dispaly: false, filter: true, export: false },
    { title: '客户名称', dataIndex: 'CUNM', key: 'CUNM', width: 220, sorter: true, dispaly: true, filter: true, export: true },
    { title: '单位编号/协议编号', dataIndex: 'DWBH', key: 'DWBH', width: 220, sorter: true, dispaly: true, filter: true, export: true },
    { title: '核心客户号', dataIndex: 'DGKHH', key: 'DGKHH', width: 140, sorter: false, dispaly: true, filter: true, export: true },
    { title: '员工号1', dataIndex: 'EMNO1', key: 'EMNO1', width: 140, sorter: true, dispaly: true, filter: true, export: true },
    { title: '员工名称1', dataIndex: 'emnm1', width: 100, dispaly: true, export: true },
    { title: '占比1', dataIndex: 'DSVL1', key: 'DSVL1', width: 120, sorter: true, dispaly: true, export: true },
    { title: '员工号2', dataIndex: 'EMNO2', key: 'EMNO2', width: 140, sorter: true, dispaly: true, filter: true, export: true },
    { title: '员工名称2', dataIndex: 'emnm2', width: 100, dispaly: true, export: true },
    { title: '占比2', dataIndex: 'DSVL2', key: 'DSVL2', width: 120, sorter: true, dispaly: true, export: true },
    { title: '员工号3', dataIndex: 'EMNO3', key: 'EMNO3', width: 140, sorter: true, dispaly: true, filter: true, export: true },
    { title: '员工名称3', dataIndex: 'emnm3', width: 100, dispaly: true, export: true },
    { title: '占比3', dataIndex: 'DSVL3', key: 'DSVL3', width: 120, sorter: true, dispaly: true, export: true },
];
const columns2 = [
    { title: '核心客户号', dataIndex: 'DGKHH', key: 'DGKHH', width: 120, dispaly: true },
    { title: '单位编号/协议编号', dataIndex: 'CUNM', key: 'CUNM', width: 200, dispaly: true },
    { title: '客户名称', dataIndex: 'DWBH', key: 'DWBH', width: 300, dispaly: true },
]
let controlsFilter = [
    { name: 'SQR', required: true, type: 'text', label: '申请人', dataType: "string", grid: 12 / 24 },
    { name: 'DGKHH', required: true, type: 'text', label: '核心客户号', dataType: "string", grid: 12 / 24 },
    { name: 'CUNM', required: true, type: 'text', label: '客户名称', dataType: "string", grid: 12 / 24 },
    { name: 'DWBH', required: true, type: 'text', label: '单位编号/协议编号', dataType: "string", grid: 12 / 24 },
    { name: 'EMNO1', required: true, type: 'text', label: '员工号1', dataType: "string", grid: 12 / 24 },
    { name: 'EMNO2', required: true, type: 'text', label: '员工号2', dataType: "string", grid: 12 / 24 },
    { name: 'EMNO3', required: true, type: 'text', label: '员工号3', dataType: "string", grid: 12 / 24 },
    { name: 'EMNO4', required: true, type: 'text', label: '员工号4', dataType: "string", grid: 12 / 24 },
    { name: 'EMNO5', required: true, type: 'text', label: '员工号5', dataType: "string", grid: 12 / 24 },
    { name: 'THSM', required: true, type: 'text', label: '认定说明', dataType: "string", grid: 12 / 24 },
    { name: 'CREATETIME', required: true, type: 'date', label: '申请时间', dataType: "date", grid: 12 / 24 },
    // { name: 'UPDATETIME', required: true, type: 'date', label: '审批时间', dataType: "date", grid: 12 / 24 },
    { name: 'UPDATETIME', required: false, type: 'text', label: '完结时间', dataType: "string", grid: 12 / 24 },
]
let controls3 = [
    { name: 'DGKHH', required: true, type: 'text', label: '核心客户号', dataType: "string", grid: 12 / 24 },
    { name: 'CUNM', required: true, type: 'text', label: '客户名称', dataType: "string", grid: 12 / 24 },
    { name: 'DWBH', required: true, type: 'text', label: '单位编号/协议编号', dataType: "string", grid: 12 / 24 },
]
let controls = [
    {
        name: 'EMNO1', required: true, type: 'disabled', label: '员工1', dataType: "string", grid: 12 / 24,
    },
    { name: 'DSVL1', required: true, type: 'number', dataType: "number", label: '占比1', grid: 12 / 24 },
    {
        name: "EMNO2", label: "员工2", type: "search", grid: 12 / 24,
        fetch: {
            daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
        },
        dataType: "string", placeholder: '请输入工号或名称...'
    },
    { name: 'DSVL2', type: 'number', dataType: "number", label: '占比2', grid: 12 / 24 },
    {
        name: "EMNO3", label: "员工3", type: "search", grid: 12 / 24,
        fetch: {
            daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
        },
        dataType: "string", placeholder: '请输入工号或名称...'
    },
    { name: 'DSVL3', type: 'number', dataType: "number", label: '占比3', grid: 12 / 24 },
    // {
    //     name: "EMNO4", label: "员工4", type: "search", grid: 12 / 24,
    //     fetch: {
    //         daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
    //     },
    //     dataType: "string", placeholder: '请输入工号或名称...'
    // },
    // { name: 'DSVL4', type: 'number', dataType: "number", label: '占比/金额4', grid: 12 / 24 },
    // {
    //     name: "EMNO5", label: "员工5", type: "search", grid: 12 / 24,
    //     fetch: {
    //         daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
    //     },
    //     dataType: "string", placeholder: '请输入工号或名称...'
    // },
    // { name: 'DSVL5', type: 'number', dataType: "number", label: '占比/金额5', grid: 12 / 24 },
    { name: 'DSDT', type: 'date', dataType: "date", label: '认定日期', grid: 12 / 24, required: true },
    { name: 'THSM', required: true, type: 'text', label: '认定说明', dataType: "string", layout: { labelSpan: 3, wrapperSpan: 20 }, placeholder: '请简要描述申请情况，以便审批...', grid: 24 / 24 },
]
let controlsImp = [
    { name: 'CUNM', required: true, type: 'text', label: '客户名称', dataType: "string", grid: 12 / 24 },
    { name: 'ACNO', required: true, type: 'text', label: '账号', dataType: "string", grid: 12 / 24 },
    { name: 'BANO', required: true, type: 'text', label: '子账号', dataType: "string", grid: 12 / 24 },
    { name: 'EMNO1', required: true, type: 'text', label: '员工1', dataType: "string", grid: 12 / 24 },
    { name: 'DSVL1', required: true, type: 'number', label: '占比1(%)', dataType: "number", grid: 12 / 24 },
    { name: 'EMNO2', required: false, type: 'text', label: '员工2', dataType: "string", grid: 12 / 24 },
    { name: 'DSVL2', required: false, type: 'number', label: '占比2(%)', dataType: "number", grid: 12 / 24 },
    { name: 'EMNO3', required: false, type: 'text', label: '员工3', dataType: "string", grid: 12 / 24 },
    { name: 'DSVL3', required: false, type: 'number', label: '占比3(%)', dataType: "number", grid: 12 / 24 },
    { name: 'EMNO4', required: false, type: 'text', label: '员工4', dataType: "string", grid: 12 / 24 },
    { name: 'DSVL4', required: false, type: 'number', label: '占比4(%)', dataType: "number", grid: 12 / 24 },
    { name: 'EMNO5', required: false, type: 'text', label: '员工5', dataType: "string", grid: 12 / 24 },
    { name: 'DSVL5', required: false, type: 'number', label: '占比5(%)', dataType: "number", grid: 12 / 24 },
    { name: 'DSDT', required: true, type: 'date', label: '认定日期', dataType: "date", grid: 12 / 24 },
    { name: 'THSM', required: true, type: 'text', label: '认定说明', dataType: "string", grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
const DataImport = dataImportCreate(daoName);
const DataTable2 = dataTableCreate("COMP_DFGZ");
const Step = Steps.Step

class DFGZDRFlow extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            range: "doing",
            stepTitle: "",
            canEdit: false,
            cunm: "",
            isClick: false
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/fetchIsManager`,
            payload: { daoName }
        });
        this.loadData()
        this.loadOptionData()
    }
    loadData() {
        const seeks = [{
            WhereItems: [{
                FieldName: "#flowType",
                Operator: "=",
                FieldValues: '' + this.state.range,
            }],
            RelationSign: "AND"
        }];
        let sorter = []
        if (this.state.range === "done") {
            sorter = {
                field: 'CREATETIME',
                order: 'descend'
            }
        }
        if (this.state.range === "all") {
            sorter = {
                field: 'CREATETIME',
                order: 'descend'
            }
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 50, seeks, sorter }
        });

    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要修改的认定关系！', 5);
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    //===============================================
    showImportHandler() {
        this.props.dispatch({
            type: `${daoName}_DataImport/setDisplay`,
            payload: { display: true },
        });
    };
    DownTmportHandler() {
        window.open(xlsxTmp)
    };
    //===============================================
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的认定关系！', 5);
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}条认定关系吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    hideEditHandler() {
        const form = this.refs.diviForm.getForm();
        form.resetFields();
        const form2 = this.refs.searchForm.getForm()
        form2.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.state.cunm = ""
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
        this.props.dispatch({
            type: `COMP_DFGZ/clearList`,
            payload: { list: [] },
        });
    };
    //延时一秒 设置isClick为false
    enableButton() {
        const that = this
        setTimeout(function () {
            that.setState({ isClick: false })
        }, 1000);
    }
    batchSubmitHandler(bType) {
        if (this.state.isClick) {
            return
        }
        this.setState({ isClick: true })
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要提交的认定关系！', 5);
            this.enableButton()
            return;
        }
        const list = this.props.list
        let runIDs = []
        let isOK = true
        list.map(row => {
            if (keys.find(key => row.ID === key)) {
                if (!row.FRID) {
                    isOK = false
                }
                runIDs.push(row.FRID)
            }
        })
        if (!isOK) {
            message.info('要提交的认定关系存在校验错误，请修改！', 5);
            this.enableButton()
            return;
        }
        bType = "agree"
        this.props.dispatch({
            type: `${daoName}/flowBatchSubmit`,
            payload: { runIDs, userID: this.props.userID, desc: "", bType },
        });
        this.cancelHandler()
        this.enableButton()
    }
    submitHandler(bType) {
        const { runID } = this.props.flowRunInfo
        bType = "agree"
        this.props.dispatch({
            type: `${daoName}/flowSubmit`,
            payload: { runID, userID: this.props.userID, desc: "", bType },
        });
        this.cancelHandler()
    }
    setExecutorHandler() {
        const { runID, currStep } = this.props.flowRunInfo
        const { checkVals } = this.state
        if (checkVals === "") {
            message.info("请您选择办理人！", 5)
        }
        this.props.dispatch({
            type: `${daoName}/setFolwExecutor`,
            payload: { runID, stepID: currStep, userIDstr: checkVals },
        });
    };
    sendBackHandler(bType) {
        const { runID, currStep } = this.props.flowRunInfo
        const { text } = this.state
        if (text === "") {
            message.info("请您填写退回意见！", 5)
            return
        }
        let bStep = 1
        let ts = "你确认要退回申请人吗"
        if (bType === "backPrev") {
            bStep = currStep - 1
            ts = "你确认要退回上一步吗"
        }
        Modal.confirm({
            title: '提示',
            content: ts,
            okText: '退回',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/flowSendBack`,
                    payload: { runID, userID: this.props.userID, backStepID: bStep, desc: text },
                });
            }
        });
    }
    abortHandler() {
        if (this.state.isClick) {
            return
        }
        this.setState({ isClick: true })
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要中止的认定关系！', 5);
            this.enableButton()
            return;
        }
        const list = this.props.list
        let runIDs = []
        let isOK = true
        list.map(row => {
            if (keys.find(key => row.ID === key)) {
                if (!row.FRID) {
                    isOK = false
                }
                runIDs.push(row.FRID)
            }
        })
        Modal.confirm({
            title: '提示',
            content: `你确认要中止此流程吗？`,
            okText: '中止',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/flowAbort`,
                    payload: { runIDs },
                });
            }
        });
        this.enableButton()
    }
    cancelHandler() {
        this.props.dispatch({
            type: `${daoName}/setFrid`,
            payload: { frid: 0 },
        });
    }
    doFlowHandler() {
        const { selectedRowKeys } = this.props
        if (selectedRowKeys.length === 0) {
            message.info("请选择要办理流程！", 5)
            return
        }
        const frid = selectedRowKeys[0]
        this.props.dispatch({
            type: `${daoName}/fetchFlowRunInfo`,
            payload: { runID: frid },
        });
    }
    rangeChangeHandler(e) {
        this.state.range = e.key
        this.loadData()
    }
    showStepHandler() {
        const len = this.props.selectedRowKeys.length;
        if (len === 0) {
            message.info('请选择要修改的认定关系！', 5);
            return;
        }
        const key = this.props.selectedRowKeys[len - 1]

        const list = this.props.list
        const index = list.findIndex(v => v.ID === key)

        const runID = list[index].FRID
        if (!runID) {
            message.info('选择的认定关系存在校验错误，请修改！', 5);
            return;
        }
        this.state.stepTitle = `${list[index].CUNM}（协议编号：${list[index].DWBH}）`
        this.props.dispatch({
            type: `${daoName}/fetchFlowRunInfo`,
            payload: { runID }
        });
    }
    hideStepHandler() {
        this.props.dispatch({
            type: `${daoName}/hideStep`,
            payload: {}
        });
    }
    onSelectChange(newList, delKeys) {
        let canEdit = false
        const oldKeys = this.props.selectedRowKeys;
        let keys = []
        oldKeys.forEach(key => {
            let isFind = false
            if (delKeys.find(key2 => key2 === key)) {
                isFind = true
            }
            if (!isFind) {
                keys.push(key)
            }
        })
        newList.forEach(row => {
            keys.push(row.ID)
        });
        const len = keys.length;
        if (len > 0) {
            const list = this.props.list
            let isOK = true
            list.map(row => {
                if (keys.find(key => row.ID === key)) {
                    if (row.step !== 1) {
                        isOK = false
                    }
                }
            })
            if (isOK) {
                canEdit = true
            }
        }
        this.setState({ canEdit })
    }
    cunmChangeHandler(e) {
        const cunm = e.target.value
        this.state.cunm = cunm
    }
    banoChangeHandler(e) {
        const bano = e.target.value
        const cunm = this.state.cunm
        if (cunm && cunm != "" && bano && bano != "") {
            this.props.dispatch({
                type: `${daoName}/fetchAcno`,
                payload: { cunm, bano }
            });
        }
    }
    renderStep() {
        const { flowRunInfo } = this.props
        const steps = flowRunInfo.stepList.map(s => {
            let desc = "未开始"
            let iszz = false
            if (flowRunInfo.state === '2' && flowRunInfo.currStep === s.id) {
                desc = "已中止"
                iszz = true
            } else if (s.state === '1') {
                desc = "办理中..."
            } else if (s.state === '2') {
                desc = "已办理"
            }
            let content = []
            s.executors.map(e => {
                let color = ""
                if (e.desc === "待办..." || e.desc === "未办") {
                    color = "gray"
                } else if (e.desc.substring(0, 2) === "中止" || e.desc === "管理员强制提交") {
                    color = "#FA541C"
                } else {
                    color = "#0D993A"
                }
                let c = <div key={e.id} ><span>{`${e.name}(${e.department})：`}</span> <br />
                    <span style={{ color: color }}>{e.desc}
                    </span>
                </div>
                content.push(c)
            })
            const descTag = <div style={{ maxHeight: "200px", overflow: "auto" }}>{content}</div>
            return <Step key={s.id} title={s.name + `【` + desc + `】`} description={descTag} />
        })
        let status = "process"
        if (flowRunInfo.state === "1") {
            status = "finish"
        } else if (flowRunInfo.state === "2") {
            status = "error"
        } else {
            const step = flowRunInfo.stepList[flowRunInfo.currStep - 1]
            if (step.appointer && step.appointer.length > 0 && step.executors.length == 0) {
                status = "wait"
            }
        }
        const current = flowRunInfo.currStep - 1
        return <Steps direction="vertical" current={current} status={status}>{steps}</Steps>
    }
    renderList() {
        let { permID, showStep, showEdit, record, userID, isManager, userName, pOrgID, selectedRowKeys } = this.props
        const { range, canEdit, isClick } = this.state
        const attachP = {
            UID: '' + userID
        }
        record.EMNO1 = userName
        record.DSTY = '1'
        const menu = <Menu onClick={this.rangeChangeHandler.bind(this)}>
            <Menu.Item key="doing">在办</Menu.Item>
            <Menu.Item key="done">已办</Menu.Item>
            {isManager ? <Menu.Item key="manager">管理</Menu.Item> : null}
            <Menu.Item key="all">全部</Menu.Item>
        </Menu>
        const butts = <ButtonGroup style={{ zIndex: 0 }}>
            <Dropdown overlay={menu} trigger={['click']}>
                <Button type="ghost" style={{ margin: 5 }}>
                    {range === "doing" ? "在办" : range === "done" ? "已办" : range === "manager" ? "管理" : "全部"}<Icon type="down" />
                </Button>
            </Dropdown>
            <Button onClick={this.showStepHandler.bind(this)}>查看进度</Button>
            {range === "doing" || range === "manager" ? <Button onClick={this.batchSubmitHandler.bind(this)} disabled={isClick}>提交</Button> : null}
            {range === "doing" && selectedRowKeys.length > 0 && !canEdit || range === "manager" ? <Button onClick={this.abortHandler.bind(this)} disabled={isClick}>中止</Button> : null}
        </ButtonGroup>
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        {butts}
                    </div>
                    <DataTable ref="diviTable" daoName={daoName} columns={columns} controls={controlsFilter} permID={permID} onSelectChange={this.onSelectChange.bind(this)} multiSelect={true} />
                    <DataImport title="认定关系导入" importName="comp_cile_divi_new" daoName={daoName} keys={["ID"]} importMode="InsertOnly" attachParams={attachP} controls={controlsImp} forbidConvert={true} saveByDao={true} />
                    {showStep ? <Modal title={this.state.stepTitle} width={400} visible={showStep} onCancel={this.hideStepHandler.bind(this)}
                        footer={null}
                    >
                        {this.renderStep()}
                    </Modal> : null}
                </div>
            </div>
        )
    }
    render() {
        return this.renderList()
    }
}
function mapStateToProps(state) {
    const { showEdit, showStep, record, list, selectedRowKeys, keyName, flowRunInfo, frid, isManager } = state[daoName];
    const { record: record2, list: list2, selectedRowKeys: selectedRowKeys2 } = state["COMP_DFGZ"];
    const { userID, orgID, pOrgID, popedomTypes, RDDate, userName, UserNo } = state.menus;
    const { display } = state[`${daoName}_DataImport`];
    return {
        loading: state.loading.models[daoName] || state.loading.models["COMP_DFGZ"],
        userID,
        orgID,
        pOrgID, userName, UserNo,
        popedomTypes,
        list,
        showEdit,
        showStep,
        selectedRowKeys,
        keyName,
        record,
        flowRunInfo,
        frid,
        showImport: display,
        record2,
        selectedRowKeys2,
        list2, RDDate, isManager
    }
}
DFGZDRFlow = connect(mapStateToProps)(DFGZDRFlow)
export default DFGZDRFlow;
let render = (props) => React.createElement(DFGZDRFlow, props);
let f = new Factory()
f.set("DFGZDRFlow", render)
